#include <gtk/gtk.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "gtkutils.h"
#include "fileutils.h"
#include "stringutils.h"

void sayHello() {
    printf("hello word\n");
}

GSList *foodlist = NULL;

#define FOOD_FILE "/tmp/foods"

void appendFoods(gpointer val, ...) {
    va_list vlist;
    va_start(vlist, val);
    while (val) {
        DEBUG_LOG("已添加午饭：%s", val);
        foodlist = g_slist_append(foodlist, val);
        val = va_arg(vlist, gpointer);
    }
    va_end(vlist);
}

void __attribute__((constructor)) before() {
    // 添加 4 个午饭选择
    appendFoods("饭", "面", "螺蛳粉", "馄炖", NULL);

    // if (FileExists(FOOD_FILE)) {
    //     int length = FileLength(FOOD_FILE);
    //     char buffer[length];
    //     FileReadToBuffer(FOOD_FILE, buffer, length);
    //     foodlist = split(buffer, '\n');
    // }
}

int i = 0;
guint timer = 0;

createGSourceObjectFunc(hand_food, GtkLabel) {
    char buffer[10000] = {0};
    i++;

    sprintf(buffer, "选择语言: "
        "<span foreground='red'>%s</span>",
        (char*) g_slist_nth(foodlist, i%g_slist_length(foodlist))->data);

    gtk_label_set_markup(source, buffer);

    return true;
}

createSignalSwappedObjectFunc(start_timer, GtkLabel) {
    if (!timerStarted(&timer))
        timer = createTimerMilliSecond(10, hand_food, user_data);
}

static void activate(GtkApplication *app, gpointer user_data) {
    GtkWindow *window = createWindowWithTitleSize(app, "午饭随机器", 200, 100);

    GtkLabel *food = createLabel("选择午饭: 等待随机..");
                        
    GtkBox *mainbox = 
        // 一组纵向小部件
        createBoxWithVerticalAppends(10, 
            food,
            // 分割线
            createSeparatorWithHorizntal(),
            // 一组横向按钮
            createBoxWithHorizntalAppends(5, 
                createButtonSwappedAction(food, "启动", (signalSwappendFunc)start_timer),
                createButtonSwappedAction(&timer, "停止", (signalSwappendFunc)stopTimer),
                NULL
            ),
            NULL
        );
    setWidgetFullMargin(mainbox, 30);

    setWindowChild(window, mainbox);
    showWindow(window);
}

int	main(int argc, char **argv) {

    GtkApplication *app;
    int status;

    app = createApplicationConnectActivate("gtk.example.template", 
                                G_APPLICATION_FLAGS_NONE, activate);
    status = runApplication(app, argc, argv);
    objectUnref(app);

    return status;
}

